package com.gdth.bank.model;

import java.util.List;

import com.gdth.bank.utils.AppUtil;
import com.gdth.business.dao.impl.BaseDaoImpl;
import com.gdth.business.server.impl.BaseServerImpl;

import org.greenrobot.greendao.AbstractDao;

import rx.Observable;
import rx.Subscriber;

/** 
 * @author  Arvin: 
 * @version 2016年5月28日 上午10:14:06 
 * 
 */
public class ServerModel<T> {
	public Observable<Long> save(final T t){
		return Observable.create(new Observable.OnSubscribe<Long>() {

			@Override
			public void call(Subscriber<? super Long> arg0) {
				// TODO Auto-generated method stub
				BaseServerImpl<T> server = new BaseServerImpl<T>();
				BaseDaoImpl<T> dao = new BaseDaoImpl<T>();
				AbstractDao mAbstractDao = AppUtil.getBaseServer(t.getClass());
				dao.setAbstractDao(mAbstractDao);
				server.setBaseDao(dao);
				Long id = server.save(t);
				
				if (id != null){
					arg0.onNext(id);
					arg0.onCompleted();
				} else{
					arg0.onError(null);
				}
			}
		});
	}
	
	public Observable<List<T>> loadAll(final T t){
		return Observable.create(new Observable.OnSubscribe<List<T>>() {

			@Override
			public void call(Subscriber<? super List<T>> arg0) {
				// TODO Auto-generated method stub
				BaseServerImpl<T> server = new BaseServerImpl<T>();
				BaseDaoImpl<T> dao = new BaseDaoImpl<T>();
				AbstractDao mAbstractDao = AppUtil.getBaseServer(t.getClass());
				dao.setAbstractDao(mAbstractDao);
				server.setBaseDao(dao);
				List<T> mList = server.loadAll();
				
				if (mList != null){
					arg0.onNext(mList);
					arg0.onCompleted();
				} else{
					arg0.onError(null);
				}
			}
		});
	}
	
	public Observable<T> delete(final T t){
		return Observable.create(new Observable.OnSubscribe<T>() {

			@Override
			public void call(Subscriber<? super T> paramT) {
				// TODO Auto-generated method stub
				BaseServerImpl<T> server = new BaseServerImpl<T>();
				BaseDaoImpl<T> dao = new BaseDaoImpl<T>();
				AbstractDao mAbstractDao = AppUtil.getBaseServer(t.getClass());
				dao.setAbstractDao(mAbstractDao);
				server.setBaseDao(dao);
				server.delete(t);
				
				paramT.onNext(t);
				paramT.onCompleted();
			}
		});
	}
	
	public Observable<T> findById(final Long id, final T t){
		return Observable.create(new Observable.OnSubscribe<T>() {

			@Override
			public void call(Subscriber<? super T> paramT) {
				// TODO Auto-generated method stub
				BaseServerImpl<T> server = new BaseServerImpl<T>();
				BaseDaoImpl<T> dao = new BaseDaoImpl<T>();
				AbstractDao mAbstractDao = AppUtil.getBaseServer(t.getClass());
				dao.setAbstractDao(mAbstractDao);
				server.setBaseDao(dao);
				T t = server.load(id);
				
				paramT.onNext(t);
				paramT.onCompleted();
			}
		});
	}
}
